package com.chatplus.application.scheduled;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.dao.pay.PayRequestDao;
import com.chatplus.application.dao.pay.RefundRequestDao;
import com.chatplus.application.domain.entity.pay.PayRequestEntity;
import com.chatplus.application.domain.entity.pay.RefundRequestEntity;
import com.chatplus.application.enumeration.PayStatusEnum;
import com.chatplus.application.enumeration.RefundStatusEnum;
import com.chatplus.application.service.pay.impl.PayProcessor;
import com.chatplus.application.service.pay.impl.RefundProcessor;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 支付结果定时任务（用户补偿可能出现的回调处理错误）
 */
@Component
public class PayTaskJob {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(PayTaskJob.class);
    private final PayProcessor payProcessor;
    private final RefundProcessor refundProcessor;

    private final RefundRequestDao refundRequestDao;
    private final PayRequestDao payRequestDao;

    public PayTaskJob(PayProcessor payProcessor,
                      RefundProcessor refundProcessor,
                      RefundRequestDao refundRequestDao,
                      PayRequestDao payRequestDao) {
        this.payProcessor = payProcessor;
        this.refundProcessor = refundProcessor;
        this.refundRequestDao = refundRequestDao;
        this.payRequestDao = payRequestDao;
    }
    /**
     * 支付结果定时任务,查询3小时之后的数据，之前的数据不查
     */
    @XxlJob(value = "PayTaskJob#payResultJob")
    public void payResultJob() {
        // 获取参数
        String param = XxlJobHelper.getJobParam();
        int minute = NumberUtil.parseInt(param);
        if (minute <= 0) {
            minute = 30;
        }
        Date requestAtGt = DateUtil.offset(new Date(), DateField.MINUTE, -minute);
        LOGGER.message("开始执行定时查询支付结果").context("开始查询时间", requestAtGt).debug();
        LambdaQueryWrapper<PayRequestEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PayRequestEntity::getPayStatus, PayStatusEnum.NOT);
        queryWrapper.gt(PayRequestEntity::getRequestAt, requestAtGt);
        List<PayRequestEntity> list = payRequestDao.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            LOGGER.message("未支付订单").context("开始查询时间", requestAtGt).context("笔数", list.size()).info();
            list.forEach(item -> payProcessor.queryPayResult(item.getId()));
        }
    }

    /**
     * 退款结果定时任务
     */
//    @XxlJob(value = "PayTaskJob#refundResultJob")
    public void refundResultJob() {
        Date now = new Date();
        // 获取参数
        String param = XxlJobHelper.getJobParam();
        int hour = NumberUtil.parseInt(param);
        if (hour <= 0) {
            hour = 3;
        }
        Date requestAtGt = DateUtil.offset(now, DateField.HOUR, -hour);
        Date requestAtLe = DateUtil.offset(now, DateField.MINUTE, -1);
        LOGGER.message("开始执行定时查询退款结果").context("开始查询时间", requestAtGt).info();
        LambdaQueryWrapper<RefundRequestEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RefundRequestEntity::getRefundStatus, RefundStatusEnum.HANDLING);
        queryWrapper.ge(RefundRequestEntity::getApplyAt, requestAtGt);
        queryWrapper.le(RefundRequestEntity::getApplyAt, requestAtLe);
        List<RefundRequestEntity> list = refundRequestDao.selectList(queryWrapper);
        LOGGER.message("未退款成功订单").context("开始查询时间", requestAtGt).context("笔数", list.size()).info();
        list.forEach(refundProcessor::queryRefund);
    }
}
